<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>TCP 聊天室前端</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
        }
        #chat-container {
            border: 1px solid #ccc;
            height: 400px;
            overflow-y: scroll;
            padding: 10px;
            margin-bottom: 10px;
        }
        #message-input {
            width: 50%;
            padding: 8px;
        }
        button {
            padding: 8px 15px;
            background-color: #4CAF50;
            color: white;
            border: none;
            cursor: pointer;
            margin: 2px;
        }
        .room-controls {
            margin-bottom: 10px;
        }
        .system-message {
            color: gray;
            font-style: italic;
        }
        .private-message {
            color: purple;
            font-weight: bold;
        }
        .my-private-message {
            color: #1a73e8;
            font-weight: bold;
        }
        .login-container {
            margin-bottom: 15px;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 5px;
        }
        .user-list {
            margin-top: 10px;
            padding: 5px;
            border: 1px solid #eee;
            max-height: 100px;
            overflow-y: auto;
        }
        .user-item {
            padding: 3px;
            cursor: pointer;
        }
        .user-item:hover {
            background-color: #f0f0f0;
        }
        input[type="text"], input[type="password"] {
            padding: 6px;
            margin: 3px 0;
            width: 150px;
        }
        .hidden {
            display: none;
        }
        .message-controls {
            margin-top: 10px;
            display: flex;
            align-items: center;
            gap: 5px;
        }
    </style>
</head>
<body>
    <div id="login-container" class="login-container">
        <h2>登录/注册</h2>
        <div>
            <input type="text" id="username" placeholder="用户名">
            <input type="password" id="password" placeholder="密码">
            <button id="login-btn">登录</button>
            <button id="register-btn">注册</button>
        </div>
    </div>

    <div id="chat-app" class="hidden">
        <h1>TCP 聊天室 - <span id="current-user"></span></h1>
        
        <div class="room-controls">
            <input type="text" id="room-input" placeholder="房间名">
            <button id="join-btn">加入房间</button>
            <button id="leave-btn">离开房间</button>
            <button id="query-users-btn">查询在线用户</button>
        </div>
        
        <div id="online-users" class="user-list hidden">
            <h4>在线用户:</h4>
            <div id="users-list"></div>
        </div>
        
        <div id="chat-container"></div>
        
        <!-- 整合消息输入和控制按钮 -->
        <div class="message-controls">
            <input type="text" id="message-input" placeholder="输入消息">
            <button id="send-btn">发送</button>
            <select id="message-type">
                <option value="0">群聊</option>
                <option value="3">私聊</option>
            </select>
            <input type="text" id="target-user" placeholder="目标用户(私聊时)" style="display: none;">
            <button id="save-record-btn">保存当前聊天记录</button>
        </div>
    </div>

    <script>
        let currentRoom = '';
        let ws;
        let currentUsername = '';
        
        // 消息类型常量定义（与后端保持一致）
        const MessageType = {
            GroupChat: 0,          // 群聊消息
            PrivateChat: 3,        // 私聊消息
            SystemMessage: 4,      // 系统消息
            StatusQuery: 5,        // 状态查询
            StatusResponse: 6,     // 状态响应
            LoginRequest: 7,       // 登录请求
            LoginResponse: 8,      // 登录响应
            RegisterRequest: 9,    // 注册请求
            RegisterResponse: 10,  // 注册响应
            SaveChatRecords: 11,   // 保存聊天记录请求
            SaveResponse: 12       // 保存结果响应
        };
        
        // 初始化连接
        function initConnection() {
            ws = new WebSocket('ws://localhost:8081/tcp-bridge');
            
            ws.onopen = function() {
                addSystemMessage("已连接到服务器");
            };
            
            ws.onmessage = function(event) {
                const msg = JSON.parse(event.data);
                displayMessage(msg);
            };
            
            ws.onclose = function() {
                addSystemMessage("与服务器的连接已断开");
            };
            
            ws.onerror = function(error) {
                addSystemMessage("连接错误: " + error);
            };
        }
        
        // 显示消息
        function displayMessage(msg) {
            const chatContainer = document.getElementById('chat-container');
            const messageDiv = document.createElement('div');
            const isOwnMessage = msg.from === currentUsername;
            
            switch(msg.type) {
                case MessageType.SystemMessage: // 系统消息
                    messageDiv.className = 'system-message';
                    messageDiv.textContent = `[系统] ${msg.content}`;
                    break;
                    
                case MessageType.PrivateChat: // 私聊消息
                    if (isOwnMessage) {
                        messageDiv.className = 'my-private-message';
                        messageDiv.textContent = `[我 -> ${msg.to}] 私聊: ${msg.content}`;
                    } else {
                        messageDiv.className = 'private-message';
                        messageDiv.textContent = `[${msg.from} -> 我] 私聊: ${msg.content}`;
                    }
                    break;
                    
                case MessageType.LoginResponse: // 登录响应
                    handleLoginResponse(msg);
                    return;
                    
                case MessageType.RegisterResponse: // 注册响应
                    handleRegisterResponse(msg);
                    return;
                    
                case MessageType.StatusResponse: // 状态响应
                    displayOnlineUsers(msg.content);
                    return;
                    
                case MessageType.SaveResponse: // 保存记录响应
                    addSystemMessage(msg.content); // 显示保存结果
                    return;
                    
                default: // 群聊消息
                    if (isOwnMessage) {
                        messageDiv.textContent = `[我@${msg.room}] : ${msg.content}`;
                    } else {
                        messageDiv.textContent = `[${msg.from}@${msg.room}] : ${msg.content}`;
                    }
            }
            
            chatContainer.appendChild(messageDiv);
            chatContainer.scrollTop = chatContainer.scrollHeight;
        }
        
        // 添加系统消息
        function addSystemMessage(text) {
            const chatContainer = document.getElementById('chat-container');
            const messageDiv = document.createElement('div');
            messageDiv.className = 'system-message';
            messageDiv.textContent = `[系统] ${text}`;
            chatContainer.appendChild(messageDiv);
            chatContainer.scrollTop = chatContainer.scrollHeight;
        }
        
        // 发送消息
        function sendMessage() {
            const input = document.getElementById('message-input');
            const messageType = parseInt(document.getElementById('message-type').value);
            const targetUser = document.getElementById('target-user').value;
            const content = input.value.trim();
            
            if (!content) return;
            
            const msg = {
                type: messageType,
                from: currentUsername,
                content: content
            };
            
            if (messageType === MessageType.PrivateChat) { // 私聊
                if (!targetUser) {
                    alert('请输入目标用户');
                    return;
                }
                msg.to = targetUser;
                
                // 立即在本地显示自己发送的私聊消息
                displayMessage({
                    type: MessageType.PrivateChat,
                    from: currentUsername,
                    to: targetUser,
                    content: content
                });
            } else { // 群聊
                if (!currentRoom) {
                    alert('请先加入一个房间');
                    return;
                }
                msg.room = currentRoom;
            }
            
            ws.send(JSON.stringify(msg));
            input.value = '';
        }
        
        // 加入房间
        function joinRoom() {
            const roomInput = document.getElementById('room-input');
            const roomName = roomInput.value.trim();
            
            if (!roomName) {
                alert('请输入房间名');
                return;
            }
            
            const msg = {
                type: 1, // 加入房间消息类型
                from: currentUsername,
                room: roomName,
                content: ''
            };
            
            ws.send(JSON.stringify(msg));
            currentRoom = roomName;
            addSystemMessage(`已加入房间: ${roomName}`);
        }
        
        // 离开房间
        function leaveRoom() {
            if (!currentRoom) {
                alert('您当前不在任何房间中');
                return;
            }
            
            const msg = {
                type: 2, // 离开房间消息类型
                from: currentUsername,
                room: currentRoom,
                content: ''
            };
            
            ws.send(JSON.stringify(msg));
            addSystemMessage(`已离开房间: ${currentRoom}`);
            currentRoom = '';
        }
        
        // 查询在线用户
        function queryOnlineUsers() {
            const msg = {
                type: MessageType.StatusQuery,
                from: currentUsername,
                content: ''
            };
            
            ws.send(JSON.stringify(msg));
            document.getElementById('online-users').classList.remove('hidden');
        }
        
        // 显示在线用户
        function displayOnlineUsers(usersData) {
            const usersList = document.getElementById('users-list');
            usersList.innerHTML = '';
            
            try {
                const statusData = JSON.parse(usersData);
                const users = statusData.Users || [];
                
                if (users.length > 0) {
                    users.forEach(user => {
                        const userItem = document.createElement('div');
                        userItem.className = 'user-item';
                        userItem.textContent = user;
                        userItem.onclick = function() {
                            document.getElementById('target-user').value = user;
                            document.getElementById('message-type').value = MessageType.PrivateChat;
                            document.getElementById('target-user').style.display = 'inline-block';
                        };
                        usersList.appendChild(userItem);
                    });
                } else {
                    usersList.innerHTML = '<div>没有在线用户</div>';
                }
            } catch (e) {
                console.error("解析用户列表失败:", e);
                usersList.innerHTML = '<div>获取用户列表失败</div>';
            }
        }
        
        // 处理登录
        function handleLogin() {
            const username = document.getElementById('username').value.trim();
            const password = document.getElementById('password').value.trim();
            
            if (!username || !password) {
                alert('请输入用户名和密码');
                return;
            }
            
            const msg = {
                type: MessageType.LoginRequest,
                content: JSON.stringify({username, password})
            };
            
            ws.send(JSON.stringify(msg));
        }
        
        // 处理登录响应
        function handleLoginResponse(msg) {
            if (msg.success) {
                currentUsername = document.getElementById('username').value.trim();
                document.getElementById('current-user').textContent = currentUsername;
                document.getElementById('login-container').classList.add('hidden');
                document.getElementById('chat-app').classList.remove('hidden');
                addSystemMessage(`欢迎 ${currentUsername} 登录成功`);
            } else {
                addSystemMessage('登录失败: ' + msg.content);
                alert('登录失败: ' + msg.content);
            }
        }
        
        // 处理注册
        function handleRegister() {
            const username = document.getElementById('username').value.trim();
            const password = document.getElementById('password').value.trim();
            
            if (!username || !password) {
                alert('请输入用户名和密码');
                return;
            }
            
            const msg = {
                type: MessageType.RegisterRequest,
                content: JSON.stringify({username, password})
            };
            
            ws.send(JSON.stringify(msg));
        }
        
        // 处理注册响应
        function handleRegisterResponse(msg) {
            if (msg.success) {
                addSystemMessage('注册成功，请登录');
                alert('注册成功，请登录');
            } else {
                addSystemMessage('注册失败: ' + msg.content);
                alert('注册失败: ' + msg.content);
            }
        }
        
        // 初始化事件监听
        document.addEventListener('DOMContentLoaded', function() {
            initConnection();
            
            // 登录/注册事件
            document.getElementById('login-btn').addEventListener('click', handleLogin);
            document.getElementById('register-btn').addEventListener('click', handleRegister);
            
            // 聊天功能事件
            document.getElementById('send-btn').addEventListener('click', sendMessage);
            document.getElementById('join-btn').addEventListener('click', joinRoom);
            document.getElementById('leave-btn').addEventListener('click', leaveRoom);
            document.getElementById('query-users-btn').addEventListener('click', queryOnlineUsers);
            
            // 回车发送消息
            document.getElementById('message-input').addEventListener('keypress', function(e) {
                if (e.key === 'Enter') sendMessage();
            });
            
            // 私聊选项切换
            document.getElementById('message-type').addEventListener('change', function() {
                const targetUser = document.getElementById('target-user');
                targetUser.style.display = this.value === '3' ? 'inline-block' : 'none';
            });

            // 绑定“保存聊天记录”按钮事件
            document.getElementById('save-record-btn').addEventListener('click', function() {
                // 检查用户是否已登录
                if (!currentUsername) {
                    alert('请先登录');
                    return;
                }

                // 获取当前聊天区域的所有消息
                const chatContainer = document.getElementById('chat-container');
                const allMessages = chatContainer.innerText;
                if (!allMessages.trim()) {
                    alert('没有可保存的聊天记录');
                    return;
                }

                // 构建保存请求
                const messageType = parseInt(document.getElementById('message-type').value);
                const saveMsg = {
                    type: MessageType.SaveChatRecords, // 使用常量确保类型正确
                    from: currentUsername,
                    content: allMessages  // 保存所有聊天内容
                };

                // 群聊时指定房间，私聊时指定目标用户
                if (messageType === MessageType.GroupChat) { // 群聊
                    if (!currentRoom) {
                        alert('请先加入房间');
                        return;
                    }
                    saveMsg.room = currentRoom;
                } else { // 私聊
                    const targetUser = document.getElementById('target-user').value;
                    if (!targetUser) {
                        alert('请指定目标用户');
                        return;
                    }
                    saveMsg.to = targetUser;
                }

                // 发送保存请求到服务端
                ws.send(JSON.stringify(saveMsg));
            });
        });
    </script>
</body>
</html>